package com.jhgsys.internal.common.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.system.dto.UserDto;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Validated
@RestController
@RequestMapping("common/")
public class CommonBasicUserController extends BaseController{
    @Autowired
    private IUserService userService;


    @GetMapping("user/page")
    public FebsResponse userPageList(User user, QueryRequest request) {
        if(StringUtils.isBlank(user.getTenantId())){
            user.setTenantId(getCurrentTenantId());
        }
        Map<String, Object> dataTable = getDataTable(getUserIPage(user, request));
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping("user/list")
    public FebsResponse userList(UserDto user) {
        if(StringUtils.isBlank(user.getTenantId())){
            user.setTenantId(getCurrentTenantId());
        }
        List<UserDto> userList = this.userService.findUserByKeywords(user);
        return new FebsResponse().success().data(userList);
    }

    private IPage<UserDto> getUserIPage(User user, QueryRequest request) {
        String currentUser = getCurrentUser().getUserName();
        IPage<UserDto> pageData = this.userService.findUserDetail(user, request);
        List<UserDto> userList = pageData.getRecords();
        if (userList != null && !userList.isEmpty()) {
            userList = userList.stream().filter(
                    u -> (!"sysadmin".equalsIgnoreCase(u.getUserName()))
            ).collect(Collectors.toList());
            pageData.setRecords(userList);
            pageData.setTotal(userList.size());
        }
        return pageData;
    }
}
